<template>
    <div class="form-boentity-edit-box">
        <div class="form-boentity-edit-btn">
            <a-button type="primary" @click="handleSubmit">
                {{ $ti18('rxForm.commitBtn','提交') }}
            </a-button>
            <a-button @click="temporaryConfig">
                {{i18n('list.Staging','暂存')}}
            </a-button>
            <a-button @click="cancel">
                {{$ti18('rxForm.closeBtn','关闭')}}
            </a-button>
        </div>
        <div class="form-boentity-edit-content">
            <a-form :form="form" layout="inline" style="background: #f0f2f5">
                <a-form-item style="display:none">
                    <a-input v-decorator="['id']"/>
                    <a-input v-decorator="['genMode',{initialValue:'create'}]"/>
                    <a-input v-decorator="['tableName']"/>
                </a-form-item>
                <rx-layout class="rxLayout">
                    <div slot="center">
                        <rx-fit>
                            <div slot="toolheader" border="false" foldbtn="false">
                                <div class="table-page-search-wrapper" style="overflow: initial;">
                                    <a-row :gutter="24">
                                        <a-col :span="8">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.category','分类')">
                                                <rx-category-select cat-key="FORM" :isGrant="true" style="width:100%;"
                                                                    v-if="isShowManageTree" :isAdmin="isManageToTree"
                                                                    v-decorator="['treeId', {rules: [{required: true, message: i18n('form.category','请选择分类','select')}]}]">
                                                </rx-category-select>
                                                <a-input v-else style="display:none;" v-decorator="['treeId']" />
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','名称')">
                                                <a-input
                                                    v-decorator="['name', {rules: [{required: true, message: i18n('form.name','请输入名称','input')}]}]"
                                                    @blur.native="getPinyinByName"
                                                    style="width:100%;"/>
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.alias','标识')">
                                                <a-input v-decorator="['alias', {rules: [
                                                    {required: true, message: i18n('form.alias','请输入标识','input')},
                                                    {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:i18n('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                                                    ]}]"
                                                         @blur.native="checkChinese(form.getFieldValue('alias'),true)"
                                                         style="width:100%;"/>
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8" v-if="!isTenant">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.ds','数据源')">
                                                <rx-input-button v-if="!dataSourceAlias.alias || pkId==null || !mdl.gendb"
                                                                 @click="openDataSource" ref="dsAlias"/>
                                                <span v-else-if="dataSourceAlias.alias=='local'">
                                                    {{i18n('form.default','默认')}}
                                                </span>
                                                <span v-else>{{ dataSourceAlias.name }}</span>
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8" v-if="pkId==null">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('genModeMap.dbReflect','库表映射')">
                                                <a-button icon="database" @click="getFromDb"></a-button>
                                            </a-form-item>

                                        </a-col>
                                        <a-col :span="8" v-else>
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('list.exiTab','存在表')">
                                                <span v-if="!mdl.gendb">
                                                    {{i18n('list.no','否')}}
                                                </span>
                                                <span v-else>
                                                    {{i18n('list.yes','是')}}
                                                </span>
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('list.isPgae','是否分页')">
                                                <a-checkbox :checked="showPage" @change="onShowPage"></a-checkbox>
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8">
                                            <a-form-item
                                                v-show="(pkId!=null && mdl.genMode!='form') || pkId==null || !mdl.gendb"
                                                :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('list.DBOperations','库操作')">
                                                <a-button style="margin-right: 5px;"
                                                          v-if="pkId!=null && mdl.genMode!='form' && mdl.gendb" icon="database"
                                                          @click="syncDbTable">
                                                    {{i18n('list.syncDBStruc','同步库表结构')}}
                                                </a-button>
                                                <a-checkbox style="margin-right: 5px;" v-if="pkId==null"
                                                            :checked="gendef==1" @change="gendefChange">
                                                    {{i18n('list.genBoMod','生成业务模型')}}
                                                </a-checkbox>
                                                <a-checkbox v-if="!mdl.gendb" v-decorator="['gendb']">
                                                    {{ i18n('list.genTable','生成物理表')}}
                                                </a-checkbox>
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="8">
                                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" >
                                                <template #label>
                                                    {{i18n('form.isBasic','基础表')}}
                                                    <a-tooltip>
                                                        <template #title>
                                                            {{i18n("msg.isBasicTooltip","应用下载时，可作为基础数据导出！")}}
                                                        </template>
                                                        <a-icon style="vertical-align: -2px" type="question-circle-o"/>
                                                    </a-tooltip>
                                                </template>
                                                <a-checkbox v-model="isBasic"></a-checkbox>
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                </div>
                            </div>

                            <a-tabs default-active-key="fields">
                                <a-tab-pane key="fields" :tab="i18n('list.entfields','实体字段')">
                                    <div class="table-containers">
                                        <div class="header-toolbar">
                                            <div class="search-box">
                                                <a-input v-model="searchVal" style="width: 300px"   :placeholder="i18n('msg.enFieldMsg','请输入要搜索的备注或字段名或属性名')"></a-input>
                                            </div>
                                            <div class="btn-box" >
                                                <a-button-group>
                                                    <template v-if="showAddButton">
                                                        <a-button @click="addRow" :title="$ti18('rxList.newBtn','添加')"><a-icon type="plus"/></a-button>
                                                    </template>
                                                    <a-button   @click="onDel" :title="$ti18('rxList.delBtn','删除')"><a-icon type="delete"/></a-button>

                                                    <a-button @click="upRow" :title="$comi18('grid.moveUp','上移')"><a-icon type="up"/></a-button>
                                                    <a-button @click="downRow" :title="$comi18('grid.movedown','下移')"><a-icon type="down"/></a-button>

                                                    <a-button   @click="onSort" :title="i18n('form.reSort','重排序')"><a-icon type="retweet" /></a-button>

                                                </a-button-group>
                                            </div>
                                        </div>
                                        <div class="grid-container">
                                            <div class="grid-container-roll">
                                                <rx-grid ref="table"
                                                         :dataSource.sync="gridData"
                                                         :allowRowSelect="true"
                                                         :multiSelect="true"
                                                         :show-page="showPage"
                                                         :columns="columns"
                                                         :id-field="'idx_'"
                                                         v-bind="showPage?pageConfig : {}"
                                                >
                                            <span slot="isPk" slot-scope="{text,record,index}">
                                                <a-radio :disabled="mdl.genMode!='db' || !getAllowChange()"
                                                         :checked="isChecked(record)"
                                                         @change.stop="pkChecked(record)" @click.stop>
                                                </a-radio>
                                            </span>
                                                    <span slot="isNotNull" slot-scope="{text,record,index}">
                                                <a-checkbox :checked="checkNotNull(record)" @click.stop
                                                            @change.stop="notNullChecked(record)"></a-checkbox>
									        </span>
                                                    <span slot="fieldName" slot-scope="{text,record,index}">
										        <a-input :disabled="!getAllowChange()" v-model.trim="record.fieldName"
                                                         @blur.native="checkChinese(record.fieldName,'fieldName',record)"/>
									        </span>
                                                    <span slot="name" slot-scope="{text,record,index}">
										        <a-input :disabled="!getAllowChange()" v-model.trim="record.name"
                                                         @blur.native="checkChinese(record.name,'attrName',record)"/>
									        </span>
                                                    <span slot="comment" slot-scope="{text,record,index}">
										        <a-input v-model="record.comment" @blur.native="getPinyin(record)"/>
									        </span>
                                                    <span slot="dbFieldType" slot-scope="{text,record,index}">
                                            <a-auto-complete :disabled="!getAllowChange()" allowClear
                                                             :getPopupContainer='p=>p.parentNode'
                                                             v-model="record.dbFieldType"
                                                             :data-source="dbFieldTypes"
                                                             @focus="getDbFieldTypes(record)"
                                                             @change="dbFieldTypeChange($event,record)"
                                                             style="width: 100%" :filter-option="filterOption">
                                            </a-auto-complete>
									</span>
                                                    <span slot="length" slot-scope="{text,record,index}">
										<a-input-number :disabled="record.dataType=='clob' || record.dataType=='date'"
                                                        :min="0" :max="4000" :step="1" v-model="record.length"/>
									</span>
                                                    <span slot="decimalLength" slot-scope="{text,record,index}">
										<a-input-number :disabled="record.dataType!='number'" :min="0" :max="50"
                                                        :step="1" v-model="record.decimalLength"/>
									</span>
                                                    <span slot="spans" slot-scope="{text,record,index}">
										<a-input-number :min="1" :max="2" :step="1" v-model="record.spans"/>
									</span>
                                    <span slot="sn" slot-scope="{text,record,index}">
										<a-input-number :min="1" :max="1000" :step="1" v-model="record.sn"/>
									</span>
                                                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                                        <span @click.stop="rowClick(record)">
                                            {{$ti18('rxList.editBtn',"编辑")}}
                                        </span>
                                      </span>
                                                    <span slot="control" slot-scope="{text,record,index}">
										<a-select allowClear :getPopupContainer='p=>p.parentNode' :options="controls" v-model="record.control"
                                                  @change="attrChange($event,'control',record)" style="width: 100%;"/>
									</span>
                                                </rx-grid>
                                            </div>
                                        </div>
                                    </div>
                                </a-tab-pane>
                                <a-tab-pane key="defField" :tab="i18n('list.standardFields','标准字段')" force-render v-if="mdl.genMode!='db'">
                                    <rx-grid ref="defFieldTable" :dataSource="defField" :allowRowSelect="false"
                                             :multiSelect="false" :showPage="false" :columns="defFieldColumns">
                                    </rx-grid>
                                </a-tab-pane>
                            </a-tabs>
                        </rx-fit>
                    </div>
                </rx-layout>
                <a-drawer class="FormBoEntityAdrawer" :title="i18n('form.fieldAttrs','字段属性')" :width="330" :placement="placement" :closable="false"
                          :zIndex="1100" :visible="aDrawerVisible"
                          @close="onClose">
                    <div class="table-page-search-wrapper align ">
                        <a-row :gutter="24" style="margin-top: 10px">
                            <a-col :span="24">
                                <a-form-item :label="i18n('form.remarks','备注')">
                                    <a-input v-model="controlJson.comment" style="width: 100%;"/>
                                </a-form-item>
                            </a-col>

                            <a-col :span="24">
                                <a-form-item :label="i18n('form.attrName','属性名')">
                                    <a-input :disabled="!getAllowChange()" v-model.trim="controlJson.name" style="width: 100%;"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item :label="i18n('form.fieldName','字段名')">
                                    <a-input :disabled="!getAllowChange()" v-model.trim="controlJson.fieldName" style="width: 100%;"/>
                                </a-form-item>
                            </a-col>

                            <a-col :span="24">
                                <a-form-item :label="i18n('form.controlType','控件类型')">
                                    <a-select allowClear :getPopupContainer='p=>p.parentNode' :options="controls"
                                              @change="attrChange($event,'control',controlJson)"
                                              v-model="controlJson.control"
                                              style="width: 100%;"/>

                                </a-form-item>
                            </a-col>

                            <a-col :span="24" v-if="controlJson.dataType=='default'">
                                    <a-form-item :label="i18n('form.mappingFields','映射字段')">
                                    <a-select allowClear :getPopupContainer='p=>p.parentNode' :options="mappingFields" @change="mappingChange"
                                              v-model="mappingField" style="width: 100%;"/>
                                </a-form-item>
                            </a-col>

                            <a-col :span="24">
                                <a-form-item :label="i18n('form.dataType','数据类型')">
                                    <a-auto-complete :disabled="!getAllowChange()"
                                                     v-model="controlJson.dbFieldType"
                                                     allowClear
                                                     :data-source="dbFieldTypes" style="width: 100%"
                                                     :getPopupContainer='p=>p.parentNode'
                                                     @focus="getDbFieldTypes(controlJson)"
                                                     :filter-option="filterOption"
                                                     @change="dbFieldTypeChange($event,controlJson)"/>
                                </a-form-item>
                            </a-col>

                            <a-col :span="24" v-if="showLength()">
                                <a-form-item :label="i18n('form.length','长度')">
                                    <a-input v-model="controlJson.length" v-if="controlJson.dataType!='number'"
                                             style="width: 100%;"/>
                                    <a-input-group v-else compact>
                                        <a-input v-model="controlJson.length" style="width: 100%;"/>
                                        <a-input-number :min="0" :max="5" v-model="controlJson.decimalLength"
                                                        style="width: 100%;"/>
                                    </a-input-group>
                                </a-form-item>
                            </a-col>

                            <a-col :span="24" v-if="showIsSingle()">
                                <a-form-item :label="i18n('form.singlevalueornot','是否单字段')">
                                    <a-select :getPopupContainer='p=>p.parentNode' @change="attrChange($event,'isSingle',controlJson)"
                                              v-model="controlJson.isSingle" style="width: 100%;">
                                        <a-select-option :key="1">
                                            {{i18n('form.single','单值')}}
                                        </a-select-option>
                                        <a-select-option :key="0">
                                            {{i18n('form.double','双值')}}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row v-if="showExtJson()">

                            <form-bo-control-ref v-model="controlJson" :fieldDatas="fields"/>
                        </a-row>
                        <a-row v-show="showSetting()">
                            <a-form-item :label="i18n('list.dataSources','数据来源')" v-if="controlJson.control!='address'">
                                <a-button @click="setSetting">
                                    {{$ti18('rxList.config','配置')}}
                                </a-button>
                            </a-form-item>
                            <a-form-item :label="$ti18('rxList.config','配置')" v-if="controlJson.control=='address'">
                                <div>
                                    <a-checkbox  v-model="controlJson.extJson.isCity" @change="changeCity">
                                        {{i18n('address.city','市')}}
                                    </a-checkbox>
                                </div>
                                <div>
                                    <a-checkbox  v-if="controlJson.extJson.isCity"  v-model="controlJson.extJson.isCounty" @change="changeCounty">
                                        {{i18n('address.county','县(区)')}}</a-checkbox>
                                </div>
                                <div>
                                    <a-checkbox v-if="controlJson.extJson.isCounty" v-model="controlJson.extJson.isAddress">
                                        {{i18n('address.address','详情地址')}}</a-checkbox>
                                </div>
                            </a-form-item>
                        </a-row>
                        <div
                            style="padding-top:10px;text-align: center; margin-top:10px;width:100%;border-top:#ccc 1px solid">
                            <a-button @click="saveAttr" type="primary" icon="save">
                                {{$ti18('rxForm.saveBtn','保存')}}
                            </a-button>
                            <a-button style="margin-left: 4px;" @click="onCancel" icon="undo">
                                {{$ti18('rxList.resetBtn','清空')}}
                            </a-button>
                            <a-button style="margin-left: 4px;" v-if="showDel()" @click="delAttr">
                                {{$ti18('rxList.delBtn','删除')}}
                            </a-button>
                        </div>
                    </div>
                </a-drawer>
                <a-modal v-model="visible" :title="i18n('msg.sql','需要执行的SQL')" @ok="handleOk" okText="已执行" :zIndex="99999"
                         :maskClosable="false">
                    <a-textarea :rows="12" v-model="executeSql"/>
                </a-modal>
                <a-modal v-model="defFieldVisible" :title="$ti18('rxList.newBtn','添加')+i18n('list.standardFields','标准字段')" @ok="handleDefFields" :zIndex="99999">
                    <a-row>
                        <a-checkbox @change="checkAll" >
                            {{$ti18('rxList.selectAll','全选')}}
                        </a-checkbox>
                    </a-row>
                    <a-checkbox-group v-model="selectFefField">
                        <a-row>
                            <a-col :span="6" v-for="field in defField">
                                <a-checkbox  :value="field.fieldName">{{field.comment}}</a-checkbox>
                            </a-col>
                        </a-row>
                    </a-checkbox-group>
                </a-modal>
            </a-form>
        </div>
    </div>
</template>
<script>
import FormBoEntityApi from '@/api/form/bo/formBoEntity'
import formBoControls from '@/api/form/bo/formBoControls'
import {
    BaseForm,
    RxDialog,
    RxLayout,
    RxInputButton,
    Util
} from "@lowcode/jpaas-common-lib";
import FormBoControlRef from './FormBoControlRef'

export default {
    name: 'FormBoEntityEdit',
    mixins: [BaseForm, formBoControls],
    components: {
        RxLayout,
        RxDialog,
        RxInputButton,
        FormBoControlRef
    },
    data() {
        return {
            //库表反射实体是否允许修改已生成表的字段属性
            allowChange:false,
            gendef: 0,
            fields: [],
            showPage:true,
            pageConfig:{
                pageSizeOptions:"['20','30','40','50']",
                defaultPageSize:40
            },
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 60,
                    dataIndex: 'serial',
                    scopedSlots: {
                        customRender: 'serial'
                    }
                },
                {
                    title: this.i18n('entField.primaryKey','主键'),
                    dataIndex: 'isPk',
                    width: 60,
                    allowCellEdit: false,
                    scopedSlots: {
                        customRender: 'isPk'
                    }
                },
                {
                    title: this.i18n('entField.isNotNull','非空'),
                    dataIndex: 'isNotNull',
                    width: 60,
                    allowCellEdit: false,
                    scopedSlots: {
                        customRender: 'isNotNull'
                    }
                },
                {
                    title: this.i18n('form.remarks','备注'),
                    dataIndex: 'comment',
                    allowCellEdit: false,
                    width: 130,
                    scopedSlots: {
                        customRender: 'comment'
                    }
                },
                {
                    title: this.i18n('form.fieldName','字段名'),
                    dataIndex: 'fieldName',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {
                        customRender: 'fieldName'
                    }
                },
                {
                    title: this.i18n('form.attrName','属性名'),
                    dataIndex: 'name',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {
                        customRender: 'name'
                    }
                },
                {
                    title: this.i18n('entField.control','控件'),
                    dataIndex: 'control',
                    width: 130,
                    allowCellEdit: false,
                    scopedSlots: {
                        customRender: 'control'
                    }
                },
                {
                    title: this.i18n('form.dataType','数据类型'),
                    dataIndex: 'dbFieldType',
                    allowCellEdit: false,
                    width: 130,
                    scopedSlots: {
                        customRender: 'dbFieldType'
                    }
                },
                {
                    title: this.i18n('form.length','长度'),
                    dataIndex: 'length',
                    allowCellEdit: false,
                    width: 80,
                    scopedSlots: {
                        customRender: 'length'
                    }
                },
                {
                    title: this.i18n('entField.decimalLength','精度'),
                    dataIndex: 'decimalLength',
                    allowCellEdit: false,
                    width: 80,
                    scopedSlots: {
                        customRender: 'decimalLength'
                    }
                },
                {
                    title: this.i18n('entField.spans','跨列'),
                    dataIndex: 'spans',
                    allowCellEdit: false,
                    width: 60,
                    scopedSlots: {
                        customRender: 'spans'
                    }
                },
                {
                    title: this.i18n('form.sn','序号'),
                    dataIndex: 'sn',
                    allowCellEdit: false,
                    width: 60,
                    scopedSlots: {
                        customRender: 'sn'
                    }
                },
                {
                    title: this.$ti18('rxList.action','操作列'),
                    dataIndex: 'action',
                    allowCellEdit: false,
                    width: 60,
                    scopedSlots: {
                        customRender: 'action'
                    }
                }
            ],
            defFieldColumns: [
                {
                    title: this.i18n('entField.comment','字段描述'),
                    dataIndex: 'comment',
                    width: 130
                },
                {
                    title: this.i18n('form.fieldName','字段Key'),
                    dataIndex: 'fieldName',
                    width: 130
                },
                {
                    title: this.i18n('form.attrName','属性别名'),
                    dataIndex: 'name',
                    width: 120
                },
                {
                    title: this.i18n('entField.dbFieldType','数据类型'),
                    dataIndex: 'dbFieldType',
                    width: 130
                }
            ],
            labelCol: {
                span: 6
            },
            wrapperCol: {
                span: 18
            },
            visible: false,
            defFieldVisible: false,
            //需要执行的sql
            executeSql: "",
            aDrawerVisible: false,
            placement: 'right',
            isTenant:false,
            selectFefField:[],

            searchVal:""
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
    },
    computed:{
      gridData(){
          let val=this.searchVal;
        if(!val){
            return this.fields;
        }
        let data = this.fields.filter(field=>{
              return field.comment.includes(val) || field.name.includes(val) || field.fieldName.includes(val)
        }) ;
        return data;
      },
      showAddButton(){
          if(this.mdl.genMode=='db' ){
              return false;
          }
          return true;
      }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        checkI18n(name,text,key){
            return this.$ti18(name,text,"formBoEntity.form",key)+this.$ti18('msg.checkMsg','要求英文+数字,英文开头!',"formBoEntity",key);
        },
        getPinyinByName(){
            let name=this.form.getFieldsValue().name
            if (!name){
                return;
            }
            if (this.form && this.form.getFieldsValue().alias){
                return;
            }
            FormBoEntityApi.getPinyin(name).then(res => {
                //去除不可见的特殊符号
                if (res) {
                    res = res.replace(/\u200B/g, '');
                }
                this.form.setFieldsValue({alias:res})
            })
        },
        onShowPage(e){
            let { checked } = e.target ;
            this.showPage = checked ;
            if(this.mdl.alias){
                Util.setKeyVal("BoEnt_" + this.mdl.alias ,checked);
            }
        },

        //关闭抽屉
        onClose() {
            this.aDrawerVisible = false;
        },
        get(id) {
            return FormBoEntityApi.getBoEnt(id,true);
        },
        save(values, vm) {
            if (!(/^[a-zA-Z][a-zA-Z0-9_]*$/g.test(values.alias))) {
                this.$notification["warning"]({
                    message: this.$ti18('rxMsa.actionTips','操作提示'),
                    description: this.checkI18n('key','标识键'),
                });
                return;
            }
            values.gendef = this.gendef;
            if (!values.gendb) {
                if (this.mdl.gendb == 1) {
                    values.gendb = 1;
                } else {
                    values.gendb = 0;
                }
            }
            //是否为基础表
            values.isBasic =this.isBasic ? 1 : 0;
            if(this.pkId){
                values.id=this.pkId;
            }
            //租户使用的实体不需要指定数据源
            if(this.isTenant){
                values.isTenant="1";
            }else {
                values.isTenant="0";
                if (this.dsAlias) {
                    var val = this.dsAlias.getVal();
                    values.dsAlias = val.value;
                    values.dsName = val.text;
                } else if (this.dataSourceAlias) {
                    values.dsAlias = this.dataSourceAlias.alias;
                    values.dsName = this.dataSourceAlias.name;
                }
            }
            var tableFields = this.fields;
            var description = this.validation(tableFields);
            if (description) {
                this.$notification["warning"]({
                    message: this.$ti18('rxMsa.actionTips','操作提示'),
                    description: description,
                    duration: 1.5
                });
                vm.loading = false;
                return;
            }
            //保存应用ID
            let appId = this.curApp.appId;
            values.appId = appId;
            values.boAttrList = tableFields.map((item, index) => {
                if (item.isPk == 1 && (!values.idField || values.idField != item.fieldName)) {
                    values.idField = item.fieldName;
                }
                if(item.control=="rx-commonfield" && item.extJson){
                    var extJson=JSON.parse(item.extJson);
                    if(extJson.mappingField){
                        if( extJson.mappingField=="UPDATE_VERSION_"){
                            values.versionField=item.fieldName;
                        }else if(extJson.mappingField=="PARENT_ID_"){
                            values.parentField=item.fieldName;
                        }else if(extJson.mappingField=="REF_ID_"){
                            values.fkField=item.fieldName;
                        }
                    }
                }
                return item;
            });
            if (!values.idField && values.gendb == 1 && values.genMode == 'db') {
                this.$notification['warning']({
                    message: this.$ti18('rxMsa.actionTips','操作提示'),
                    description: this.i18n('msg.selectKey','请选择主键！'),
                });
                vm.loading = false;
                return;
            }
            var self = this;
            if(values.gendb==1){
                this.$confirm({
                    title: this.$ti18('rxMsa.actionTips','操作提示'),
                    content: this.i18n('msg.sumitMsg','你确定提交并生成到数据库吗?'),
                    okText: this.$ti18('rxForm.ackBtn','确认'),
                    cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                    zIndex: 99999,
                    onOk() {
                        self.saveBoEnt(vm,self,values);
                    },
                    onCancel() {
                        vm.loading = false;
                        return;
                    },
                });
            }else {
                self.saveBoEnt(vm,self,values);
            }
        },
        saveBoEnt(vm,self,boEnt){
            FormBoEntityApi.saveBoEnt(boEnt).then(res => {
                if (res && res.data && res.data.length > 0) {
                    var arySql = [];
                    for (var i = 0; i < res.data.length; i++) {
                        arySql.push(res.data[i].sql);
                    }
                    this.executeSql = arySql.join("\r\n");
                    self.visible = true;
                    vm.loading = false;
                    Object.assign(self.mdl, boEnt);
                } else {
                    if (res.success) {
                        Util.closeWindow(self, "ok");
                    } else {
                        vm.loading = false;
                        return;
                    }
                }
            });
        },
        gendefChange(e) {
            if (e.target.checked) {
                this.gendef = 1;
            } else {
                this.gendef = 0;
            }
        },
        showDefFields() {
            this.selectFefField=[];
            this.defFieldVisible=true;
        },
        //添加标准字段
        handleDefFields(){
            //存放已存在的字段名
            var message="";
            var fields_ = this.fields;
            for (let i = 0; i < this.selectFefField.length; i++) {
                //查询是否存在
                var field = this.fields.find((item) => this.selectFefField[i] == item.fieldName);
                if (!field) {
                    var defField = this.defField.find((item) => this.selectFefField[i] == item.fieldName);
                    fields_.push(defField);
                }else {
                    //已存在的字段
                    if(message==""){
                        message+=field.fieldName;
                    }else {
                        message+=","+field.fieldName;
                    }
                }
            }
            if(message!=""){
                this.$message.warning(message+"等字段名已存在!");
            }
            this.fields = fields_;
            this.defFieldVisible=false;
        },
        checkAll(e){
            this.selectFefField=[];
            if(e.target.checked){
                for (let i = 0; i < this.defField.length; i++) {
                    this.selectFefField.push(this.defField[i].fieldName);
                }
            }
        },
        isChecked(record) {
            return record.isPk == 1;
        },
        checkNotNull(record) {
            return record.isNotNull == 1;
        },
        notNullChecked(record) {
            if (record.isNotNull == 0) {
                record.isNotNull = 1;
            } else {
                record.isNotNull = 0;
            }
        },
        pkChecked(record) {
            this.fields.forEach(item => {
                if (record.idx_ == item.idx_) {
                    record.isPk = 1;
                    record.isNotNull = 1;
                } else {
                    item.isPk = 0;
                }
            });
        },
        syncDbTable() {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('msg.overwriteMsg','你确定要覆盖当前库表结构?'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                zIndex: 99999,
                onOk() {
                    self.loadByTable(self.mdl.tableName, self.mdl.dsAlias, self.mdl.genMode);
                    self.$message.success('同步完成!')
                },
                onCancel() {
                },
            });

        },
        handleOk() {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('msg.executeSqlMsg','你确定sql已执行且都执行成功了吗?'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                zIndex: 99999,
                onOk() {
                    FormBoEntityApi.saveBoEnt(self.mdl, true).then(res => {
                        if (res && res.success) {
                            self.visible = false;
                            Util.closeWindow(self, "ok");
                        }
                        self.$message.success(res.message);
                    });
                },
                onCancel() {
                },
            });

        },
        getPinyin(record) {
            if (!record.comment || record.name || record.fieldName) return;
            FormBoEntityApi.getPinyin(record.comment).then(res => {
                //去除不可见的特殊符号
                if (res) {
                    res = res.replace(/\u200B/g, '');
                }
                record.name = res;
                record.fieldName = res;
            })
        },
        /**
         * 验证数据
         * @param tableFields
         * @returns {string}
         */
        validation(tableFields) {
            for (var i = 0; i < tableFields.length; i++) {
                if (tableFields[i].comment == "" || tableFields[i].name == "" || tableFields[i].fieldName == "") {
                    return this.i18n('msg.valid',"备注、字段名、属性名不能为空!");
                }
                if(!this.checkChinese(tableFields[i].name,false)){
                    return this.checkI18n('attrNameTips',[tableFields[i].comment,tableFields[i].name]);
                }
                if(!this.checkChinese(tableFields[i].fieldName,false)){
                    return this.checkI18n('fieldNameTips',[tableFields[i].comment,tableFields[i].fieldName]);
                }
                var extJson;
                if(tableFields[i].extJson && typeof(tableFields[i].extJson)=="string" ){
                    extJson=JSON.parse(tableFields[i].extJson);
                }else {
                    extJson=tableFields[i].extJson;
                }
                if(tableFields[i].control=="rx-commonfield" && this.mdl.genMode == 'db'){
                    if(!extJson.mappingField){
                        return tableFields[i].comment + this.i18n('msg.noMapMsg','未配置映射字段!');
                    }
                }
                for (var j = i + 1; i < tableFields.length; j++) {
                    if (j == tableFields.length) {
                        break;
                    }
                    if (tableFields[i].fieldName == tableFields[j].fieldName) {
                        return tableFields[i].fieldName + this.i18n('msg.dupName','字段名重复!');
                    }
                }
                //需配置关联字段的属性 双值且不为表单生成方式
                if(tableFields[i].isSingle==0 && this.mdl.genMode == 'db' ){
                    if(tableFields[i].control=="address"){
                        if(!extJson.province){
                            return tableFields[i].comment + this.i18n('msg.noProvince','未配置省名称!');
                        }
                    }else {
                        if(!extJson.ref){
                            return tableFields[i].comment + this.i18n('msg.noAsso','未配置关联字段!');
                        }
                    }
                }
            }
            return "";
        },
        //获取库表反射实体是否允许修改字段属性
        getAllowChange(){
            if(this.mdl.genMode!='db' ){
                return true;
            }
            return this.allowChange || this.pkId==null || !this.mdl.gendb ;
        },
        //暂存字段校验
        temValidate(tableFields){
            for (var i = 0; i < tableFields.length; i++) {
                if(!this.checkChinese(tableFields[i].name,false)){
                    return this.checkI18n('attrNameTips',[tableFields[i].comment,tableFields[i].name]);
                }
                if(!this.checkChinese(tableFields[i].fieldName,false)){
                    return this.checkI18n('fieldNameTips',[tableFields[i].comment,tableFields[i].fieldName]);
                }
            }
            return "";
        },
        //暂存字段配置
        temporaryConfig(vm){
            var self=this;
            //暂存字段也要校验
            var tableFields = self.fields;
            var description = self.temValidate(tableFields);
            if (description) {
                self.$notification["warning"]({
                    message: self.$ti18('rxMsa.actionTips','操作提示'),
                    description: description,
                    duration: 1.5
                });
                vm.loading = false;
                return;
            }
            this.form.validateFields((err, values) => {

                if(err) {
                    return;
                }
                var tableFields=self.fields
                values.boAttrList = tableFields.map((item, index) => {
                    if (item.isPk == 1 && (!values.idField || values.idField != item.fieldName)) {
                        values.idField = item.fieldName;
                    }
                    if(item.control=="rx-commonfield" && item.extJson){
                        var extJson=JSON.parse(item.extJson);
                        if(extJson.mappingField){
                            if( extJson.mappingField=="UPDATE_VERSION_"){
                                values.versionField=item.fieldName;
                            }else if(extJson.mappingField=="PARENT_ID_"){
                                values.parentField=item.fieldName;
                            }else if(extJson.mappingField=="REF_ID_"){
                                values.fkField=item.fieldName;
                            }
                        }
                    }
                    return item;
                });
                values.pkId=this.pkId;
                if(this.isTenant){
                    values.isTenant="1";
                }else {
                    values.isTenant = "0";
                    if (this.dsAlias) {
                      var val = this.dsAlias.getVal();
                      values.dsAlias = val.value;
                      values.dsName = val.text;
                    } else if (this.dataSourceAlias) {
                      values.dsAlias = this.dataSourceAlias.alias;
                      values.dsName = this.dataSourceAlias.name;
                    }
                }
                //保存应用ID
                let appId = this.curApp.appId;
                values.appId = appId;
                FormBoEntityApi.temporarySave(values).then(res=>{
                    if(res && res.success){
                        self.pkId=res.data.id;
                    }
                });
            })
        },
        checkChinese(val,showMessage,message){
            if(!val){ return true }
            if (!(/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(val))) {
                if(showMessage){
                    let msg = '';
                    if(showMessage === 'fieldName' && message){
                        msg = this.checkI18n('fieldNameTips',[message.comment,message.fieldName]);
                    }else if(showMessage === 'attrName' && message){
                        msg = this.checkI18n('attrNameTips',[message.comment,message.name]);
                    }else {
                        msg = message || this.checkI18n('alias','"别名要求英文+数字,英文开头!"')
                    }
                    this.$notification["warning"]({
                        message: this.$ti18('rxMsa.actionTips','操作提示'),
                        description: msg,
                        duration: 3
                    })
                }
                return false;
            }
            return true;
        }
    },
    watch:{
        "mdl.isTenant":function (val){
            if(val && val=="1"){
                this.isTenant=true;
            }
        }
    }
}
</script>
<style scoped>
.form-boentity-edit-btn{
    padding:6px 10px;
    text-align: right;
    border-bottom: 1px solid #ddd;
}
.form-boentity-edit-btn button{
    margin-left: 6px;
}
.rxLayout >>> .ant-tabs-bar{
    margin-bottom: 0;
}
.rxLayout >>> .fit-header{
    padding-bottom: 0!important;
}
.form-boentity-edit-box,
.table-containers{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.header-toolbar{
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
}
.form-boentity-edit-content,
.grid-container{
    flex: 1;
    position: relative;
}
.grid-container-roll{
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
}

.FormBoEntityAdrawer >>> .ant-drawer-body {
    padding: 0px !important;
}

.ant-row {
    padding-right: 10px;
}

.ant-form {
    height: 100%;
}

.table-operator button {
    margin-right: 6px;
}

.ant-form-inline .ant-form-item {
    display: flex;
}

.align >>> .ant-form-item-label {
    width: 90px;
}

.align >>> .ant-row {
    margin-right: 0;
}

.table-page-search-wrapper.align {
    height: 100%;
}
.table-page-search-wrapper >>> .ant-form-item{
    margin-bottom: 4px!important;
    margin-right: 0!important;
}
.table-page-search-wrapper >>> .ant-row {
    display: flex;
    flex-flow: wrap;
}

.dialogs >>> .content-div {
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
}

.ant-divider-horizontal {
    margin: 5px 0;
}
</style>
